package logic

import (
	"context"
	"database/sql"
	"encoding/json"
	"errors"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
	"go-zero-project-02/model_study/user/model"
	"time"

	"go-zero-project-02/model_study/user/api/internal/svc"
	"go-zero-project-02/model_study/user/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LoginLogic) Login(req *types.LoginRequest) (resp string, err error) {
	userName := req.UserName
	password := req.Password
	one, err := l.svcCtx.UsersModel.FindOneByUserNameAndPassword(context.Background(), userName, password)
	if err != nil && !errors.Is(err, sqlx.ErrNotFound) {
		logx.Infof("查询: %v", err)
		return "", nil
	}
	if one != nil {
		marshal, _ := json.Marshal(one)
		return string(marshal), nil
	}

	//增加
	add, _ := l.svcCtx.UsersModel.Insert(context.Background(), &model.User{
		Username: sql.NullString{
			String: userName,
			Valid:  true,
		},
		Password: sql.NullString{
			String: password,
			Valid:  true,
		},
		RegisterTime:  time.Now(),
		LastLoginTime: time.Now(),
	})
	id, _ := add.LastInsertId()
	logx.Infof("增加: %v", id)

	//查找
	//one, err := l.svcCtx.UsersModel.FindOne(l.ctx, 1)
	//if err != nil {
	//	return "", nil
	//}
	//logx.Infof("查找: %v", one)

	// 修改
	//err = l.svcCtx.UsersModel.Update(context.Background(), &models.User{
	//	Username: sql.NullString{
	//		String: "fengfeng1",
	//		Valid:  true,
	//	},
	//	Password: sql.NullString{
	//		String: "123456",
	//		Valid:  true,
	//	},
	//	Id: id,
	//})
	//logx.Infof("修改: %v", id)

	// 删除
	//l.svcCtx.UsersModel.Delete(context.Background(), id)
	//logx.Infof("删除: %v", id)

	return "ok", nil
}
